package jam.network.message;

import jam.Base64;
import jam.model.*;
import jam.network.*;

import java.io.File;
import java.io.IOException;
import java.util.*;

//
// =============================================================================
//

public class ClientRequestGetAvatar extends ClientCommand {
	protected static final String KEYWORD = "CR_AVATAR";
	private String username;
	
	//
	// =========================================================================
	//
	
	@Override
	public void process(ClientController controller) {
		NetworkController network = controller.getNetworkController();
        ClientModel client = controller.getModel();
        ServerModel server = network.getModel();
        
        // try and get the user
        User avatarUser = new User();
        Map<String, String> avatarSearch = new HashMap<String, String>();
        avatarSearch.put("email", this.username);
        if (avatarUser.populate(avatarSearch) == false) {
        	controller.send(new ServerResponse(this, false));
            return;
        }
        
        // Make sure the avatar exists
        String avatarPath = String.format("data/%s", avatarUser.getUsername());
        File avatar = new File(avatarPath);
        if (avatar.exists() == false) {
        	controller.send(new ServerResponse(this, false));
        	return;
        }
        
        // Try and load the daturrrs
        String imageData;
        try {
			imageData = Base64.encodeFromFile(avatarPath);
		} catch (IOException e) {
			controller.send(new ServerResponse(this, false));
            return;
		}
        
        List<String> responseArgs = new LinkedList<String>();
        responseArgs.add(imageData);
        
        // TODO: Send the avatar
        controller.send(new ServerResponse(
        		this, 
        		true,
        		responseArgs));
	}
	
	//
    // =========================================================================
    //
    
    @Override
    protected String getKeyword() { 
        return ClientRequestGetAvatar.KEYWORD; 
    }
    
	//
	// =========================================================================
	//
	
	protected ClientRequestGetAvatar(int transactionId, Scanner args) {
		super(transactionId);
		
		// Get arguments.
		this.username = args.next();
	}
}
